<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;
use app\common\plugin\HookRegistry;

/**
 * 钩子系统管理命令
 */
class HookCommand extends Command
{
    protected static $defaultName = 'hook:manage';
    protected static $defaultDescription = '钩子系统管理工具';

    protected function configure()
    {
        $this->addOption('stats', 's', InputOption::VALUE_NONE, '显示钩子统计信息')
            ->addOption('list', 'l', InputOption::VALUE_NONE, '列出所有钩子')
            ->addOption('reload', 'r', InputOption::VALUE_NONE, '重新加载钩子')
            ->addOption('test', 't', InputOption::VALUE_NONE, '运行性能测试');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        // 初始化钩子系统
        HookRegistry::initialize();

        if ($input->getOption('stats')) {
            $this->showStats($output);
        } elseif ($input->getOption('list')) {
            $this->listHooks($output);
        } elseif ($input->getOption('reload')) {
            $this->reloadHooks($output);
        } elseif ($input->getOption('test')) {
            $this->runPerformanceTest($output);
        } else {
            $this->showHelp($output);
        }

        return Command::SUCCESS;
    }

    private function showStats(OutputInterface $output)
    {
        $stats = HookRegistry::getStats();

        $output->writeln('<info>钩子系统统计信息</info>');
        $output->writeln('==================');
        $output->writeln("总事件数: {$stats['total_events']}");
        $output->writeln("总监听器数: {$stats['total_listeners']}");
        $output->writeln("内存使用: " . round($stats['memory_usage'] / 1024 / 1024, 2) . " MB");
        $output->writeln("初始化状态: " . ($stats['initialized'] ? '已初始化' : '未初始化'));

        if ($stats['total_listeners'] > 0) {
            $avg_listeners = round($stats['total_listeners'] / $stats['total_events'], 2);
            $output->writeln("平均每个事件监听器数: {$avg_listeners}");
        }
    }

    private function listHooks(OutputInterface $output)
    {
        $hooks = HookRegistry::getAllHooks();

        $output->writeln('<info>所有钩子列表</info>');
        $output->writeln('==============');

        foreach ($hooks as $event_name => $priorities) {
            $listener_count = 0;
            foreach ($priorities as $priority => $callbacks) {
                $listener_count += count($callbacks);
            }

            $output->writeln("<comment>{$event_name}</comment> ({$listener_count}个监听器)");

            foreach ($priorities as $priority => $callbacks) {
                foreach ($callbacks as $callback) {
                    $output->writeln("  - 优先级{$priority}: {$callback['plugin']}::{$callback['class']}::{$callback['method']}");
                }
            }
            $output->writeln('');
        }
    }

    private function reloadHooks(OutputInterface $output)
    {
        $output->writeln('<info>重新加载钩子系统...</info>');

        $start_time = microtime(true);
        HookRegistry::reload();
        $end_time = microtime(true);

        $reload_time = ($end_time - $start_time) * 1000;
        $stats       = HookRegistry::getStats();

        $output->writeln('<info>钩子系统重新加载完成</info>');
        $output->writeln("加载时间: " . round($reload_time, 2) . " ms");
        $output->writeln("加载了 {$stats['total_events']} 个事件，{$stats['total_listeners']} 个监听器");
    }

    private function runPerformanceTest(OutputInterface $output)
    {
        $output->writeln('<info>运行钩子性能测试...</info>');

        // 简单的性能测试
        $test_hooks = ['template.head', 'template.footer', 'content.bottom'];
        $iterations = 1000;

        foreach ($test_hooks as $hook_name) {
            $start_time = microtime(true);

            for ($i = 0; $i < $iterations; $i++) {
                hook($hook_name, "test_{$i}");
            }

            $end_time       = microtime(true);
            $execution_time = ($end_time - $start_time) * 1000;
            $avg_time       = $execution_time / $iterations;

            $output->writeln(sprintf(
                "钩子 %-20s: %d次调用, 总时间 %6.2fms, 平均 %6.4fms",
                $hook_name,
                $iterations,
                $execution_time,
                $avg_time
            ));
        }
    }

    private function showHelp(OutputInterface $output)
    {
        $output->writeln('<info>钩子系统管理工具</info>');
        $output->writeln('==================');
        $output->writeln('可用选项:');
        $output->writeln('  --stats, -s    显示钩子统计信息');
        $output->writeln('  --list, -l     列出所有钩子');
        $output->writeln('  --reload, -r   重新加载钩子');
        $output->writeln('  --test, -t     运行性能测试');
        $output->writeln('');
        $output->writeln('示例:');
        $output->writeln('  php webman hook:manage --stats');
        $output->writeln('  php webman hook:manage --list');
        $output->writeln('  php webman hook:manage --reload');
    }
}
